package com.dbq.fast.business.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dbq.fast.App;
import com.dbq.fast.R;
import com.dbq.fast.analysis.EventConstant;
import com.dbq.fast.analysis.YibaAnalysis;
import com.dbq.fast.business.h5.H5ContainerActivity;
import com.dbq.fast.business.login.bean.CustomProfile;
import com.dbq.fast.business.login.business.NewLoginBiz;
import com.dbq.fast.business.main.MainActivity;
import com.dbq.fast.business.me.help.CountDownUtil;
import com.dbq.fast.common.base.BaseActivity;
import com.dbq.fast.common.bean.User;
import com.dbq.fast.util.PhoneFormatCheckUtils;
import com.dbq.fast.util.ProgressDialogUtil;
import com.dbq.fast.util.SpUtil;
import com.dbq.fast.util.SystemUtil;
import com.dbq.fast.util.WindowToastUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.dbq.fast.business.h5.H5ContainerActivity.WHICH_IS_PRIVACY;
import static com.dbq.fast.business.login.business.NewLoginBiz.REASON_ACCOUNT_IS_EXIST;

public class NewLoginActivity extends BaseActivity implements NewLoginBiz.LoginListener {

    public static final String HAS_LOGIN_SUCCESS = "hasLoginSuceess";
    private static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[_-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
    public static final int REGISTER = 0x01;
    public static final int BIND_PWD = 0x02;
    public static final int LOGIN = 0x03;

    //验证码
    @BindView(R.id.phone_number)
    EditText phoneNumber;
    @BindView(R.id.access_verifi_code)
    TextView accessVerifiCode;
    @BindView(R.id.verification_code)
    EditText verificationCode;
    @BindView(R.id.check_verifi_code)
    Button checkVerifiCode;
    @BindView(R.id.switch_login)
    TextView switchLogin;
    @BindView(R.id.verification_code_area)
    RelativeLayout verifiCodeArea;
    //绑定密码
    @BindView(R.id.input_pwd)
    EditText inputPwd;
    @BindView(R.id.input_pwd_again)
    EditText inputPwdAgain;
    @BindView(R.id.bind_pwd_area)
    LinearLayout bindPwdArea;
    @BindView(R.id.bind_pwd)
    Button bindPwd;
    //登录
    @BindView(R.id.account)
    EditText account;
    @BindView(R.id.pwd)
    EditText pwd;
    @BindView(R.id.reset_pwd)
    TextView resetPwd;
    @BindView(R.id.login_area)
    RelativeLayout loginArea;
    @BindView(R.id.switch_register)
    TextView switchRegister;
    //用户协议
    @BindView(R.id.checkbox)
    CheckBox checkbox;
    @BindView(R.id.agree_area)
    LinearLayout agreeArea;

    private int curWitch = REGISTER;
    private NewLoginBiz loginBiz;
    private CountDownUtil countDownUtil;
    private TextWatcher textWatcherPhone = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (charSequence.toString().trim().length() == 11) {
                accessVerifiCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_access_verifi_code_enable));
                accessVerifiCode.setAlpha(1);
                accessVerifiCode.setTextColor(getResources().getColor(android.R.color.white));
                accessVerifiCode.setEnabled(true);
            } else {
                accessVerifiCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_access_verifi_code_disable));
                accessVerifiCode.setAlpha(0.5f);
                accessVerifiCode.setTextColor(getResources().getColor(R.color.verifi_code_grey));
                accessVerifiCode.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        boolean flag = SpUtil.getBoolean(HAS_LOGIN_SUCCESS, false);
        if (User.getInstance().isLogin()) {
            goMainPage();
            return;
        }
        YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_OPEN_WELCOME);
        setContentView(R.layout.activity_new_login);
        ButterKnife.bind(this);

        bindPwd.setText(getString(R.string.register));
        loginBiz = new NewLoginBiz(this);
        loginBiz.setLoginListener(this);
        showWitch(LOGIN);
        initListener();

    }

    private void initListener() {
        phoneNumber.addTextChangedListener(textWatcherPhone);
    }

    public void showWitch(int witch) {
        curWitch = witch;
        accessVerifiCode.setVisibility(witch == REGISTER ? View.VISIBLE : View.GONE);
        verifiCodeArea.setVisibility(witch == REGISTER ? View.VISIBLE : View.GONE);
        bindPwdArea.setVisibility(witch == BIND_PWD ? View.VISIBLE : View.GONE);
        loginArea.setVisibility(witch == LOGIN ? View.VISIBLE : View.GONE);
        agreeArea.setVisibility(witch == LOGIN ? View.GONE : View.VISIBLE);

        switchLogin.setText(witch == REGISTER ? Html.fromHtml(getString(R.string.tip_switch_login)) : "");
        switchRegister.setText(witch == LOGIN ? Html.fromHtml(getString(R.string.tip_switch_register)) : "");
    }

    @OnClick({R.id.access_verifi_code, R.id.check_verifi_code, R.id.switch_login, R.id.user_agreement, R.id.switch_register, R.id.bind_pwd, R.id.login, R.id.reset_pwd})
    public void onView(View view) {
        switch (view.getId()) {
            case R.id.access_verifi_code:
                accessVerifiCodeOp();
                break;
            case R.id.check_verifi_code:
                checkVerifiCodeOp();
                break;
            case R.id.switch_login:
            case R.id.switch_register:
                showWitch(curWitch == REGISTER ? LOGIN : REGISTER);
                break;
            case R.id.user_agreement:
                goPrivacyPage();
                break;
            case R.id.bind_pwd:
                bindPwdOp();
                break;
            case R.id.login:
                loginOp();
                break;
            case R.id.reset_pwd:
                resetPwdOp();
                break;
        }
    }

    /**
     * 重置密码
     */
    private void resetPwdOp() {
        Intent intent = new Intent(NewLoginActivity.this, ResetPwdActivity.class);
        startActivity(intent);
    }

    /**
     * 获取验证码
     */
    private void accessVerifiCodeOp() {
        if (!SystemUtil.isNetworkAvailable(App.getContext())) {
            WindowToastUtils.showShort(App.getContext(), getString(R.string.tip_check_net_available));
            return;
        }
        String phoneNumberStr = phoneNumber.getText().toString().trim();
        boolean isPhoneLegal = PhoneFormatCheckUtils.isPhoneLegal(phoneNumberStr);
        if (!isPhoneLegal) {
            WindowToastUtils.showShort(App.getContext(), getString(R.string.phone_format_error));
            return;
        }
        accessVerifiCode.setEnabled(false);
        checkVerifiCode.setEnabled(true);
        checkVerifiCode.setAlpha(1);
        verificationCode.requestFocus();
        loginBiz.requestVerCode(phoneNumberStr);
        countDownUtil = new CountDownUtil(accessVerifiCode)
                .setCountDownMillis(60_000L)//倒计时60000ms
                .setCountDownColor(android.R.color.white, android.R.color.white)//不同状态字体颜色
                .start();
    }

    /**
     * 校验验证码
     */
    private void checkVerifiCodeOp() {
        if (!checkVerifiCode.isEnabled()) return;
        if (!SystemUtil.isNetworkAvailable(App.getContext())) {
            WindowToastUtils.showShort(App.getContext(), getString(R.string.tip_check_net_available));
            return;
        }
        String phoneNumberStr = phoneNumber.getText().toString().trim();
        String verifiCodeStr = verificationCode.getText().toString().trim();
        boolean isPhoneLegal = PhoneFormatCheckUtils.isPhoneLegal(phoneNumberStr);
        if (!isPhoneLegal) {
            WindowToastUtils.showShort(App.getContext(), getString(R.string.phone_format_error));
            return;
        } else if ("".equals(verifiCodeStr)) {
            WindowToastUtils.showShort(App.getContext(), getString(R.string.verifi_code_null));
            return;
        } else if (!checkbox.isChecked()) {
            WindowToastUtils.showShort(App.getContext(), getString(R.string.tip_not_agree));
            return;
        }
        ProgressDialogUtil.showProgress(this, "", getString(R.string.waiting), true);
        loginBiz.checkVerCode(phoneNumberStr, verifiCodeStr);
//        accessVerifiCode.setVisibility(View.GONE);
    }

    /**
     * 绑定密码(注册)
     */
    private void bindPwdOp() {
        if (!SystemUtil.isNetworkAvailable(App.getContext())) {
            WindowToastUtils.showShort(App.getContext(), getString(R.string.tip_check_net_available));
            return;
        }
        String inputPwdStr = inputPwd.getText().toString().trim();
        String confirmPwdStr = inputPwdAgain.getText().toString().trim();
        if ("".equals(inputPwdStr) || "".equals(confirmPwdStr)) {
            WindowToastUtils.showShort(App.getContext(), getString(R.string.tip_input_can_not_null));
            return;
        } else if (!inputPwdStr.equals(confirmPwdStr)) {
            WindowToastUtils.showShort(App.getContext(), getString(R.string.tip_pwd_not_same));
            return;
        } else if (!checkbox.isChecked()) {
            WindowToastUtils.showShort(App.getContext(), getString(R.string.tip_not_agree));
            return;
        }
        ProgressDialogUtil.showProgress(this, "", getString(R.string.waiting));
        String phoneNumberStr = phoneNumber.getText().toString().trim();
        String captcha = verificationCode.getText().toString().trim();
        loginBiz.register(phoneNumberStr, inputPwdStr, captcha);
    }

    /**
     * 登录
     */
    private void loginOp() {
        if (!SystemUtil.isNetworkAvailable(App.getContext())) {
            WindowToastUtils.showShort(App.getContext(), getString(R.string.tip_check_net_available));
            return;
        }
        String accountStr = account.getText().toString().trim();
        String pwdStr = pwd.getText().toString().trim();
        if ("".equals(accountStr) || "".equals(pwdStr)) {
            WindowToastUtils.showShort(App.getContext(), getString(R.string.tip_account_pwd_is_null));
            return;
        } else if (!PhoneFormatCheckUtils.isPhoneLegal(accountStr)) {
            WindowToastUtils.showShort(App.getContext(), getString(R.string.tip_phone_format_error));
            return;
        }
        ProgressDialogUtil.showProgress(this, "", getString(R.string.waiting));
        loginBiz.login(accountStr, pwdStr);
    }

    private void goPrivacyPage() {
        Intent intent = new Intent(NewLoginActivity.this, H5ContainerActivity.class);
        intent.putExtra("which", WHICH_IS_PRIVACY);
        startActivity(intent);
    }

    private void goMainPage() {
        SpUtil.setBoolean(HAS_LOGIN_SUCCESS, true);
        startActivity(new Intent(NewLoginActivity.this, MainActivity.class));
        finish();
    }

    @Override
    public void loginSuccess(CustomProfile profile) {
        if (!isResume) return;
        ProgressDialogUtil.hideProgress();
        WindowToastUtils.showShort(App.getContext(), getString(R.string.tip_login_success), R.color.green_succ);
        goMainPage();
    }

    @Override
    public void loginFail(int type, String reason) {
        if (!isResume) return;
        ProgressDialogUtil.hideProgress();
        WindowToastUtils.showShort(App.getContext(), reason);
        if (type == REASON_ACCOUNT_IS_EXIST) {
            if (countDownUtil != null) {
                countDownUtil.reset();
            }
            if (accessVerifiCode != null) {
                accessVerifiCode.setEnabled(true);
            }
        }
    }

    @Override
    public void checkVerCode(boolean isOk) {
        if (!isResume) return;
        ProgressDialogUtil.hideProgress();
        if (isOk) {
            showWitch(BIND_PWD);
        } else {
            WindowToastUtils.showShort(App.getContext(), getString(R.string.tip_verifi_code_error));
        }
    }

    @Override
    public void resetPwd(boolean isOk, String msg) {

    }
}
